<template>
  <div>
    <h2 class="template-title">新增合同模板</h2>
    <el-form :model="fieldList" ref="formRef">
      <div v-for="(item, i) in fieldList" :key="i" class="row">
        <el-form-item >
          <el-input
              v-model="item.columnName"
              clearable
              :placeholder="i === 0 ? '表英文名' : '字段英文名'">
          </el-input>
          <el-input
              v-model="item.LabelCN"
              clearable
              :placeholder="i === 0 ? '表中文名' : '字段中文名'">
          </el-input>
        </el-form-item>
        <el-button circle icon="el-icon-plus" @click="addList"></el-button>
        <el-button circle icon="el-icon-minus" @click="subList(i)" v-show="fieldList.length > 1"></el-button>
      </div>
      <el-button type="primary" @click="addTemplate" v-show="fieldList.length > 2">创建模板</el-button>
    </el-form>
  </div>
</template>

<script>
import {createTemplate} from "./api.js";

export default {
  data() {
    return {
      fieldList: [{ columnName: '', LabelCN: '' }]
    }
  },
  methods: {
    addList() {
      this.fieldList.push({ columnName: '', LabelCN: '' });
    },
    subList(index) {
      if (this.fieldList.length > 1) {
        this.fieldList.splice(index, 1);
      }
    },
    flattenRequestData(requestData){
      let flatData = {
        tableName: requestData.tableName,
        tableCN: requestData.tableCN
      };

      // 展开 fields，传递为多个单独的字段
      for (let key in requestData.fields) {
        if (requestData.fields.hasOwnProperty(key)) {
          flatData[`fields[${key}]`] = requestData.fields[key];
        }
      }

  return flatData;
},
    addTemplate() {
      const tableName = this.fieldList[0].columnName;
      const tableCN = this.fieldList[0].LabelCN;

      const fields = {};
      for (let i = 1; i < this.fieldList.length; i++) {
        const item = this.fieldList[i];
        if (item.columnName && item.LabelCN) {
          fields[item.columnName] = item.LabelCN;
        }
      }

      const requestData = {
        tableName: tableName,
        tableCN: tableCN,
        fields: fields
      }

      console.log('Request Data:', requestData);

      const flatData = this.flattenRequestData(requestData)  // 扁平化 fields
      createTemplate(flatData)
          .then(response => {
            console.log('模板创建成功:', response);
            window.location.reload(); // 刷新整个页面
          })
          .catch(error => {
            console.error('模板创建失败:', error);
          })
    }
  }
}
</script>

<style scoped>
.row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.template-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}
</style>
